package com.lwj.framework.config;

import java.lang.reflect.Method;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.lwj.framework.constant.Constant;
import com.lwj.framework.util.RedisCacheUtil;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;

public class CacheConfiguration extends CachingConfigurerSupport {
	/**
	 * 根据方法名签名生成缓存key
	 * springboot使用缓存
	 * 1.配置类添加 @EnableCaching
	 * 2.方法添加注解@Cacheable(cacheManager = Constant.RedisCacheManager, cacheNames = Constant.ShortTimeCache)
	 * Constant.ShortTimeCache ：在ehcache.xml文件上配置
	 * @return
	 */
	@Bean(name = Constant.CacheKeyGenerator)
	@Override
	public KeyGenerator keyGenerator() {
		return new KeyGenerator() {
			@Override
			public Object generate(Object target, Method method, Object... params) {
				StringBuilder sb = new StringBuilder();
				sb.append(target.getClass().getName());
				sb.append(".").append(method.getName());
				for (Object obj : params) {
					sb.append(obj.toString());
				}
				return sb.toString();
			}
		};
	}

	@Primary
	@Bean(name = Constant.EhCacheManager)
	public EhCacheCacheManager ehCacheManager() {
		EhCacheManagerFactoryBean ehCacheManagerFactoryBean = new EhCacheManagerFactoryBean();
		ehCacheManagerFactoryBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
		ehCacheManagerFactoryBean.setShared(true);
		return new EhCacheCacheManager(ehCacheManagerFactoryBean.getObject());
	}

	@Bean(name = Constant.RedisCacheManager)
	public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
		// 生成一个默认配置，通过config对象即可对缓存进行自定义配置
		RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
		// 对每个缓存空间应用不同的配置
		Map<String, Long> cacheMap = RedisCacheUtil.readCacheXml(new ClassPathResource("ehcache.xml"));
		Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
		for (Entry<String, Long> item : cacheMap.entrySet()) {
			configMap.put(item.getKey(), config.entryTtl(Duration.ofSeconds(item.getValue())));
		}
		// 初始化, 注意下两句的调用顺序，一定要先调用该方法设置初始化的缓存名，再初始化相关的配置
		RedisCacheManager cacheManager = RedisCacheManager.builder(factory).initialCacheNames(cacheMap.keySet())
				.withInitialCacheConfigurations(configMap).build();
		return cacheManager;
	}

	@Bean(name = Constant.RedisTemplate)
	public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<Object, Object> template = new RedisTemplate<Object, Object>();
		template.setConnectionFactory(redisConnectionFactory);
		// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值（默认使用JDK的序列化方式）
		Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
		ObjectMapper mapper = new ObjectMapper();
		mapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
		mapper.enableDefaultTyping(DefaultTyping.NON_FINAL);
		serializer.setObjectMapper(mapper);
		template.setValueSerializer(serializer);
		// 使用StringRedisSerializer来序列化和反序列化redis的key值
		template.setKeySerializer(new StringRedisSerializer());
		template.afterPropertiesSet();
		return template;
	}

	@Bean(name = Constant.StringRedisTemplate)
	public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
		StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
		stringRedisTemplate.setConnectionFactory(redisConnectionFactory);
		return stringRedisTemplate;
	}

}
